package com.visizen.wisdomclass.server.action.User;

import com.alibaba.fastjson.JSONObject;
import com.visizen.wisdomclass.server.action.response.ErrorCode;
import com.visizen.wisdomclass.server.action.response.ErrorCodeManager;
import com.visizen.wisdomclass.server.action.response.Result;
import com.visizen.wisdomclass.server.model.WcUser;
import com.visizen.wisdomclass.server.service.UserService;
import com.visizen.wisdomclass.server.util.WCDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 【用户】 注册新用户
 *
 * @author: chenjian
 */
@Controller
@RequestMapping(value = "/User")
public class UserRegisterAction {
    /**
     * 注册新用户
     *
     * @param token
     * @param username    用户名
     * @param passmd5     密码的md5值
     * @param fullname    名字
     * @param attachId    头像id
     * @param sex         性别
     * @param birthday    生日
     * @param mobilephone 手机号码
     * @param email       邮箱
     * @param request
     * @return
     */
    @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
    @ResponseBody
    public Result registerUser(@RequestParam(required = false) String token, String username, String passmd5, String fullname,
                               long attachId, String sex, String birthday, String mobilephone, String email, HttpServletRequest request) {
        Result result = new Result();
        JSONObject jo = new JSONObject();
        WcUser user = new WcUser();
        user.setAttach_id(attachId);
        user.setEmail(email);
        user.setMobilephone(mobilephone);
        user.setFullname(fullname);
        user.setPassmd5(passmd5);
        user.setSex(sex);
        user.setUsername(username);
        user.setRegistertime(WCDate.toDateTime(new Date()));
        user.setBirthday(WCDate.toDate(birthday));
        boolean isSucc = userService.registerUser(user);
        /**
         * 判断用户是否注册成功
         */
        if (!isSucc) {
            /**
             * 注册失败
             */
            ErrorCodeManager codeManager = ErrorCodeManager.getLocalMsg(ErrorCode.C1024_userRegisterFailed);
            jo.put("exception", "");
            result.setFailedResult(request, codeManager.getCode(), codeManager.getMsg(), jo);
        } else {
            /**
             * 注册成功
             */
            result.setSuccessResult(request, "", null);
        }
        return result;
    }

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
